package com.security.core.validate.code.impl;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import com.security.core.validate.code.ValidateCode;
import com.security.core.validate.code.ValidateCodeException;
import com.security.core.validate.code.ValidateCodeGenerator;
import com.security.core.validate.code.ValidateCodeProcessor;
import com.security.core.validate.code.ValidateCodeType;

/**
 * @author liukang
 * @version 1.0.0
 * @title AbstractValidateCodeProcessor
 * @description 默认的验证码生成impl
 * @date 2019年5月22日
 */
public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {

    /**
     * @description 操作session的工具类
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * @description 搜集系统中所有validateCodeGenerator接口的实现
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;


    /**
     * 验证码三步
     * 生成
     * 保存
     * 发送
     */
    @Override
    public void create(ServletWebRequest request) throws Exception {
        C validateCode = generator(request);
        save(request, validateCode);
        send(request, validateCode);
    }


    /**
     * @param request
     * @return
     * @title generator
     * @description 根据不同的类型生成不同的验证码
     * @author Dark_blue
     * @date 2019年8月12日
     */
    @SuppressWarnings("unchecked")
    private C generator(ServletWebRequest request) {
        String type = getProcessorType(request);
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(type + "CodeGenerator");
        return (C) validateCodeGenerator.generator(request);
    }

    /**
     * @param request
     * @param validateCode
     * @title save
     * @description 保存验证码到session中
     * @author Dark_blue
     * @date 2019年8月12日
     */
    private void save(ServletWebRequest request, C validateCode) {
        ValidateCode code = new ValidateCode(validateCode.getCode(), validateCode.getExpireTime());
        sessionStrategy.setAttribute(request, SESSION_KEY_PREFIX + getProcessorType(request).toUpperCase(), code);
    }

    /**
     * @param request
     * @param validateCode
     * @throws Exception
     * @title send
     * @description 发送验证码，由子类实现
     * @author Dark_blue
     * @date 2019年8月12日
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;


    /**
     * @param request
     * @return
     * @title getProcessorType
     * @description 根据请求的url获取校验码的类型
     * @author Dark_blue
     * @date 2019年8月12日
     */
    private String getProcessorType(ServletWebRequest request) {
        return StringUtils.substringAfter(request.getRequest().getRequestURI(), "/code/");
    }

    /**
     *
     */
    @SuppressWarnings("unchecked")
    @Override
    public void validate(ServletWebRequest servletWebRequest) {
        ValidateCodeType validateCodeType = getValidateCodeType();
        String sessionKey = getSessionKey();

        C codeInSession = (C) sessionStrategy.getAttribute(servletWebRequest, sessionKey);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), validateCodeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            e.printStackTrace();
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(validateCodeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(validateCodeType + "验证码不存在");
        }

        if (codeInSession.isExpried()) {
            sessionStrategy.removeAttribute(servletWebRequest, sessionKey);
            throw new ValidateCodeException(validateCodeType + "验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(validateCodeType + "验证码不匹配");
        }

        sessionStrategy.removeAttribute(servletWebRequest, sessionKey);
    }

    /**
     * @param servletWebRequest
     * @return
     * @title getValidateCodeType
     * @description 根据url获取校验码的类型
     * @author Dark_blue
     * @date 2019年8月28日
     */
    private ValidateCodeType getValidateCodeType() {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }

    /**
     * @param servletWebRequest
     * @return
     * @title getSessionKey
     * @description 构建验证码生成时放入session的key
     * @author Dark_blue
     * @date 2019年8月28日
     */
    private String getSessionKey() {
        return SESSION_KEY_PREFIX + getValidateCodeType().toString().toUpperCase();
    }
}
